*---海外关联公司处理
gen year=substr( EndDate,1,4)    //生成统计截至年份
replace EndDate=year
drop year
rename EndDate year
destring year,replace
destring Symbol,replace
gen estabyear=substr( EstablishDate ,1,4)
destring estabyear,replace
gen age=year- estabyear
sort Symbol year
bys Symbol year:gen set=_n
bys Symbol year:gen number=_N
keep if set==1
drop set
save affiliate
*------合并
merge 1:1 Symbol year using "company"
drop if _merge==1
drop _merge
save company_affiliate,replace
*------
drop if IsTaxHaven==1    //扔掉注册地为注册天堂
gen innov=1 if RelationshipID=="1"|RelationshipID=="2"|RelationshipID=="3"
replace innov=0 if innov==.
sort Symbol year
egen number=group(year)
///生成第一次开设海外结构的年份,此后年份数据为1
gen lian=innov
sort Symbol year
egen tag=tag(Symbol innov) if innov!=0
bys Symbol :gen sumtag=sum(tag)
replace sumtag=. if innov==0
bys Symbol : egen year0=min(sumtag*year)
replace lian=1 if year>year0
drop tag sumtag
save temple
*------合并专利数量
merge 1:1 Symbol year using "A:\数据库\上市公司专利申请和授权数据1990-2021年数据\上市公司专利申请和授权数据_上市公司本身.dta"
keep if _merge==3
drop _merge
gen lnsqfm=log(1+ 当年联合申请的发明数量)
gen lnsqsy=log(1+ 当年联合申请的实用新型数量)
gen lnsqwg=log(1+ 当年联合申请的外观设计数量)
save lian_patent,replace

*----描述性统计*---------------------------------------------------------------------------------------------------
use lian_patent,clear
local xx " qua1 lian age TobinQ Lev ROA ROE Cashflow tec "  //引号中是想要展示在表中的变量
    logout, save(mytable1) word replace:       ///  
            tabstat `xx', stat(N mean sd min max) format(%10.2f) c(s)

			use tiaojie,clear
local xx " analyst supply INTL ATO innoefficiency04 RDSpendSumRatio "  //引号中是想要展示在表中的变量
    logout, save(mytable1) word replace:       ///  
            tabstat `xx', stat(N mean sd min max) format(%10.2f) c(s)
			
*--------------------------------------------------------------------------------------------------------------------			
*----基准回归
//发明专利申请数量(高端创新)
xtreg lnsqfm lian age TobinQ Lev ROA Cashflow i.year,fe
//总数量
xtreg lnzsq lian age TobinQ Lev ROA Cashflow i.year,fe
//实用+发明申请数（低端创新）
xtreg diduan lian age TobinQ Lev ROA Cashflow i.year,fe
//总申请数量
gen qua1=(3*lnsqfm+2* lnsqsy+lnsqwg)/6
gen lnqua1=log(1+qua1)

xtreg lnqua1 lian  i.year,fe
est store fee_1
xtreg lnqua1 lian age i.year,fe
est store fee_2
xtreg lnqua1 lian age TobinQ i.year,fe
est store fee_3
xtreg lnqua1 lian age TobinQ Lev i.year,fe
est store fee_4
xtreg lnqua1 lian age TobinQ Lev ROA i.year,fe
est store fee_5
xtreg lnqua1 lian age TobinQ Lev ROA ROE i.year,fe
est store fee_6
xtreg lnqua1 lian age TobinQ Lev ROA ROE Cashflow i.year,fe
est store fee_7

esttab fee_*  using final1.rtf, replace                  ///
						mtitle(`m') compress nogap b(%6.3f)       ///
						scalars(r2_a N F) star(* 0.1 ** 0.05 *** 0.01)	
*----平行性检验
gen policy=year-year0 if lian!=0
tab policy
replace policy = -5 if policy <= -5
replace policy = 5 if policy > =5

tab policy,gen(ac)
forvalues i=1/11{
replace ac`i'=0 if ac`i'==.
}
drop ac1
//画图
xtreg qua1 ac* age TobinQ Lev ROA Cashflow i.year,fe

coefplot,baselevels  ///
keep(ac*) ///
vertical ///
yline(0,lcolor(edkblue*0.8))  ///加入y=0这条虚线
xline(5,lwidth(vthin)lpattern(shortdash) lcolor(tea1))     ///加入x=0垂直虚线
ylabel(,labsize(*0.75)) xlabel(,labsize(*0.75))   ///横纵坐标轴大小
ytitle("政策效应") xtitle("政策前后") ///
addplot(line @b @at)  ///
ciopts(lpattern(dash) recast(rcap) msize(medium))   ///
scheme(s1mono)level(95)  ///
coeflabels(ac2="-4" ac3="-3" ac4="-2" ac5="-1" ac6="0" ac7="1" ac8="2" ac9="3" ac10="4" ac11="5" ) 
save temp1

*-------反事实检验
//改变政策时间的安慰剂检验 政策时间提前
xtset Symbol year
gen ac_3=year0-3
gen t_3=0
replace t_3=1 if year>ac_3
gen treated_3=0 if ac_3>2222
replace treated_3=1 if ac_3<2222
gen did_3=treated_3*t_3
xtreg qua1 did_3 age TobinQ Lev ROA Cashflow i.year,fe //不显著


//个体安慰剂检验/法1
use temp1,clear
permute qua1 beta = _b[lian],  ///  前边解释变量 括号放解释变量
   reps(500) seed(123) saving("simulations.dta",replace):     ///  重复1000次
   xtreg qua1 lian age TobinQ Lev ROA Cashflow i.year,fe
               ///  回归方程
			   //画图 
   use "simulations.dta", clear
   set scheme s2color
   #delimit ; 
   dpplot beta, msymbol(Oh)              // 修改样本点的风格
     xline(  0.235  , lc(black*0.5) lp(dash))       // 基准回归的系数，此处换上正确的回归系数
     xline(0, lc(black*0.5) lp(solid))       // 安慰剂正态分布对称轴实线
     xtitle("Policy",height(7))      
     xlabel(-0.1(0.05)0.25, format(%6.3f) labsize(small))    //设置横纵轴及单位长度
     ytitle("Density", size(*0.8)) 
     ylabel(, nogrid format(%4.1f) labsize(small)) 
     note("") caption("")           // 图表备注内容
     graphregion(fcolor(white)) ;  

	 //法2
	use temp1,clear
	permute lian beta = _b[lian] se = _se[lian] df = e(df_r), ///
 reps(500) seed(123) saving("simulations2.dta"): ///
xtreg qua1 lian age TobinQ Lev ROA Cashflow i.year,fe

//画图 系数
	use simulations2
#delimit ;
dpplot beta,  msymbol(Oh)         
 xline(0.235, lc(black*0.5) lp(dash))
 xline(0, lc(black*0.5) lp(solid))
 xlabel(-0.1(0.05)0.25)
    xtitle("Estimator", size(*0.8)) xlabel(, format(%4.1f) labsize(small))
    ytitle("Density", size(*0.8)) ylabel(, nogrid format(%4.1f) labsize(small)) 
    note("") caption("") graphregion(fcolor(white)) ;
#delimit cr

	///画图 系数和 p 值结合(不好看)
	use simulations2
	gen p_value = 2 * ttail(df, abs(beta/se))
	gen t_value=beta/se
#delimit ;
twoway (scatter p_value beta)(kdensity beta, yaxis(2)), 
 xline(0.235, lc(black*0.5) lp(dash))
 xline(0, lc(black*0.5) lp(solid)) 
 yline(0.055, lc(black*0.5) lp(dash))
 xlabel(-0.1(0.05)0.25)
 xtitle("Estimator", size(*0.8)) xlabel(, format(%4.1f) labsize(small))
 ytitle("Density", size(*0.8)) ylabel(, nogrid format(%4.1f) labsize(small)) 
 ytitle("P Value", size(*0.8) axis(2)) ylabel(, nogrid format(%4.1f) labsize(small) axis(2))
 legend(r(1) order(1 "P Value" 2 "Estimator"))
 graphregion(color(white)) ;
#delimit cr

*-------其他稳健性检验

//更换指标
     
use tiaojie,clear
gen lnqua1=log(1+qua1)
*-*------高维固定
reghdfe  qua1 lian  TobinQ Lev ROA ROE Cashflow ,absorb(Symbol year IndustryCode CITYCODE) vce(r)
est store f3_1
  //替换解释变量
	   *-----国际化程度
reghdfe qua1 INTL  TobinQ Lev ROA ROE Cashflow  , absorb(Symbol year IndustryCode CITYCODE) vce(r)
est store f3_2
*----对外投资额
merge 1:1 Symbol year using "C:\Program Files\stata\ofid.dta"
keep if _merge==3
drop _merge
reghdfe qua1 lnofdi age TobinQ Lev ROA Cashflow, absorb(Symbol year IndustryCode) vce(r) //对外投资的对数额
*----国外专利数量
 merge 1:1 Symbol year using "patentforeign"
drop if _merge==2
drop _merge
gen lnpatents=log(1+ patents)
xtreg lnqua1 lnpatents age TobinQ Lev ROA Cashflow ROE i.year,fe //负的 (国外专利数量)
*----跨国并购
merge m:1 Symbol year using "binggou"
drop if _merge==2
drop _merge
save 跨国并购
reghdfe qua1 binggou  TobinQ Lev ROA ROE Cashflow  , absorb(Symbol year IndustryCode ) vce(r) //显著为正
est store f3_3
    
	//替换被解释变量
reghdfe lnsqfm lian TobinQ Lev ROA ROE Cashflow,absorb(Symbol year IndustryCode) vce(r) //发明专利申请数量
est store f3_4
reghdfe  lnzsq lian TobinQ Lev ROA ROE Cashflow ,absorb(Symbol year IndustryCode) vce(r)	 //总专利申请数量
est store f3_5
//更换模型
nbreg qua1 lian   TobinQ Lev ROA ROE Cashflow ,r nolog   //负二项回归
	est store f3_6
*---------
esttab f3_*  using fina3.rtf, replace                  ///
						mtitle(`m') compress nogap b(%6.3f)       ///
						scalars(r2_a N F) star(* 0.1 ** 0.05 *** 0.01)	
*-------------------------------******************************-------------------------------------------------
	   //PSMDID
use temp1,clear
sort Symbol year
bys Symbol:egen q=sum(lian)
gen treat=1 if q!=0
replace treat=0 if treat==.
gen after=lian 
replace after=. if treat==0

global xlist "TobinQ ATO ROE Lev ROA Cashflow Size"
global regopt "absorb(Symbol year IndustryCode ) clu(Symbol) keepsing"
gen lnqua1=log(1+qua1)
save temple3,replace
///logit求企业做出融入全球创新网络决策的概率
probit lian age ATO Size ROE Lev ROA Cashflow ,r nolog
est store f1_1
reghdfe  lnqua1 lian  TobinQ Lev ROA ROE Cashflow ,absorb(Symbol year IndustryCode) vce(r)
est store f1_2
*---------
esttab f1_*  using final2.rtf, replace                  ///
						mtitle(`m') compress nogap b(%6.3f)       ///
						scalars(r2_a N F) star(* 0.1 ** 0.05 *** 0.01)	
//////////ATT ATU
set seed 0001
gen ranorder=runiform()
sort ranorder
 psmatch2 treat TobinQ ATO ROE Lev ROA Cashflow Size, out(qua1)logit ties ate neighbor(1) common caliper(.05) odds


*------------
forvalue i = 2000/2021 {
   preserve 
       capture {
	   keep if year==`i' 
	   set seed 0000
	   gen norvar_2 = rnormal()
	   sort norvar_2
	   
	   psmatch2 treat $xlist, outcome(qua1) logit neighbor(1)  ties common ate caliper(0.05)
					
					save `i',replace
	   }
    restore  
      } 

clear all

use 2000.dta,clear
forvalue k=2001/2021{
     capture{
	 append using `k'.dta
	 }

}

save ybydata,replace
 
         //倾向得分值的核密度图
		 use ybydata,clear
		 sum _pscore if treat==1,detail  //处理组的倾向得分均值0.6613
		 *---匹配前
sum _pscore if treat == 0, detail

twoway(kdensity _pscore if treat == 1, lpattern(solid)                     ///
              lcolor(black)                                                  ///
              lwidth(thin)                                                   ///
              scheme(qleanmono)                                              ///
              ytitle("{stSans:核}""{stSans:密}""{stSans:度}",                ///
                     size(medlarge) orientation(h))                          ///
              xtitle("{stSans:匹配前的倾向得分值}",                          ///
                     size(medlarge))                                         ///
              xline(0.6613 , lpattern(solid) lcolor(black))                ///
              xline(`r(mean)', lpattern(dash)  lcolor(black))                ///
              saving(kensity_yby_before, replace))                           ///
      (kdensity _pscore if treat == 0, lpattern(dash)),                    ///
      xlabel(0(0.2)1 , labsize(medlarge) format(%02.1f))                        ///
      ylabel(0(1)5, labsize(medlarge))                                       ///
      legend(label(1 "{stSans:处理组}")                                      ///
             label(2 "{stSans:控制组}")                                      ///
             size(medlarge) position(1) symxsize(10))

graph export "kensity_yby_before.emf", replace

discard


*- 匹配后

sum _pscore if treat == 0 & _weight != ., detail

twoway(kdensity _pscore if treat == 1, lpattern(solid)                     ///
              lcolor(black)                                                  ///
              lwidth(thin)                                                   ///
              scheme(qleanmono)                                              ///
              ytitle("{stSans:核}""{stSans:密}""{stSans:度}",                ///
                     size(medlarge) orientation(h))                          ///
              xtitle("{stSans:匹配后的倾向得分值}",                          ///
                     size(medlarge))                                         ///
              xline(0.6613   , lpattern(solid) lcolor(black))                ///
              xline(`r(mean)', lpattern(dash)  lcolor(black))                ///
              saving(kensity_yby_after, replace))                            ///
      (kdensity _pscore if treat == 0 & _weight != ., lpattern(dash)),     ///
      xlabel( 0(0.2)1    , labsize(medlarge) format(%02.1f))                        ///
      ylabel(0(1)5, labsize(medlarge))                                       ///
      legend(label(1 "{stSans:处理组}")                                      ///
             label(2 "{stSans:控制组}")                                      ///
             size(medlarge) position(1) symxsize(10))

graph export "kensity_yby_after.emf", replace

discard

   ///psm回归
reghdfe qua1 lian  TobinQ Lev ROA ROE Cashflow if _weight!=., $regopt  //使用权重不为空的样本
  est store f1_3
  reghdfe qua1 lian  TobinQ Lev ROA ROE Cashflow if _support==1, $regopt  //满足共同支撑假设
  est store f1_4
 gen weight=_weight*2
  replace weight=1 if treat==1&_weight!=.
  reghdfe qua1 lian  TobinQ Lev ROA  ROE Cashflow [fweight=weight], $regopt  //使用频数加权回归  buxianzhu
  est store f1_5
 *---------
esttab f1_*  using final12.rtf, replace                  ///
						mtitle(`m') compress nogap b(%6.3f)       ///
						scalars(r2_a N F) star(* 0.1 ** 0.05 *** 0.01)	
 
*------------------------------------------------------------------------------------------------------------------
 
*---------
	*----机制分析
	use lian_patent,clear
	merge 1:1 Symbol year using "attention_supply_international_digital"
keep if _merge==3
drop _merge
gen lnqua1=log(1+qua1)
save tiaojie 

 use tiaojie,clear
*analyst sttention
reghdfe qua1  c.lian##c.analyst  TobinQ Lev ROA ROE Cashflow, absorb(Symbol year IndustryCode) vce(r) //正
est store ff_1
*supply chain
reghdfe qua1  c.lian##c.supply  TobinQ Lev ROA ROE Cashflow, absorb(Symbol year  IndustryCode) vce(r)  //负
est store ff_2
*uncerty
merge 1:1 Symbol year using "uncerty"
keep if _merge==3
drop _merge
reghdfe qua1  c.lian##c.EU经行业调整后 TobinQ Lev ROA ROE Cashflow, absorb( year  IndustryCode ) vce(r) //显著为负
est store ff_3
*数字化转型
merge 1:1 Symbol year using "digitalscore"
keep if _merge==3
drop _merge
reghdfe qua1  c.lian##c.digital  TobinQ Lev ROA Cashflow ROE, absorb(Symbol year  IndustryCode) vce(r)  //显著为正
reghdfe  digitalapplicationscoring lian TobinQ Lev ROA Cashflow ROE, absorb(Symbol year IndustryCode) vce(r)  
//显著为正
est store f4_1

esttab ff_*  using fina41.rtf, replace                  ///
						mtitle(`m') compress nogap b(%6.3f)       ///
						scalars(r2_a N F) star(* 0.1 ** 0.05 *** 0.01)	
*---------
esttab f4_*  using fina41.rtf, replace                  ///
						mtitle(`m') compress nogap b(%6.3f)       ///
						scalars(r2_a N F) star(* 0.1 ** 0.05 *** 0.01)	

*--yanfatouru 
use lian_patent,clear
merge 1:1 Symbol year using "RD"
keep if _merge==3
drop _merge
reghdfe qua1  c.lian##c.RDSpendSumRatio TobinQ Lev ROA Cashflow ROE, absorb(Symbol year  IndustryCode) vce(r)  //正
reghdfe RDSpendSumRatio lian , absorb(Symbol year) vce(r)  //正 加了控制变量之后不显著
est store f4_2

*----经营效率
reghdfe lnqua1  c.lian##c.ATO  TobinQ Lev ROA Cashflow ROE, absorb(Symbol year  IndustryCode) vce(r) //正
reghdfe  ATO  lian TobinQ Lev ROA Cashflow ROE, absorb(Symbol year IndustryCode) vce(r)
est store f4_3
*---创新成功率/转化率
replace RDSpendSum = RDSpendSum/100000 //单位：百万
sort Symbol year
gen innoefficiency01 = (F1.当年联合获得专利总和)/(RDSpendSum +0.8*L1.RDSpendSum )
gen innoefficiency02 = (F1.当年联合获得专利总和)/(RDSpendSum+0.8*L1.RDSpendSum+0.6*L2.RDSpendSum)
gen innoefficiency03 = (F1.当年联合获得专利总和)/(RDSpendSum+0.8*L1.RDSpendSum+0.6*L2.RDSpendSum+0.4*L3.RDSpendSum)
gen innoefficiency = (F1.当年联合获得专利总和)/(RDSpendSum+0.8*L1.RDSpendSum+0.6*L2.RDSpendSum+0.4*L3.RDSpendSum+0.2*L4.RDSpendSum)

reghdfe lnqua1  c.lian##c.innoefficiency TobinQ Lev ROA Cashflow ROE, absorb(Symbol year  IndustryCode) vce(r) //正
est store f4_4

reghdfe innoefficiency lian TobinQ Lev ROA Cashflow ROE , absorb(Symbol year) vce(r)



esttab f4_*  using final4.rtf, replace                  ///
						mtitle(`m') compress nogap b(%6.3f)       ///
						scalars(r2_a N F) star(* 0.1 ** 0.05 *** 0.01)	

*----高管团队技术社会资本
use lian_patent,clear
merge 1:1 Symbol year using "gaoguantechnology"
keep if _merge==3
drop _merge
reghdfe qua1 c.lian##c.tec TobinQ Lev ROA Cashflow ROE, absorb(Symbol year  IndustryCode) vce(r) //正

reghdfe tec lian TobinQ Lev ROA Cashflow ROE, absorb(Symbol year  IndustryCode) vce(r) //正
est store f4_5

*---------
esttab f4_*  using final4.rtf, replace                  ///
						mtitle(`m') compress nogap b(%6.3f)       ///
						scalars(r2_a N F) star(* 0.1 ** 0.05 *** 0.01)	

*------------异质性分析
	use lian_patent,clear
*----高/低创新资源城市
gen highinnov=1 if CITY=="深圳市"|CITY=="北京市"|CITY=="广州市"|CITY=="天津市"|CITY=="石家庄市"|CITY=="唐山市"|CITY=="秦皇岛市"|CITY=="太原市"|CITY=="呼和浩特市"|CITY=="包头市"|CITY=="沈阳市"|CITY=="大连市"|CITY=="长春市"|CITY=="哈尔滨市"|CITY=="上海市"|CITY=="南京市"|CITY=="常州市"|CITY=="连云港市"|CITY=="镇江市"|CITY=="南通市"|CITY=="泰州市"|CITY=="扬州市"|CITY=="盐城市"|CITY=="无锡市"|CITY=="苏州市"|CITY=="湖州市"|CITY=="杭州市"|CITY=="宁波市"|CITY=="嘉兴市"|CITY=="合肥市"|CITY=="福州市"|CITY=="厦门市"|CITY=="南昌市"|CITY=="景德镇市"|CITY=="萍乡市"|CITY=="济南市"|CITY=="青岛市"|CITY=="济宁市"|CITY=="烟台市"|CITY=="郑州市"|CITY=="洛阳市"|CITY=="南阳市"|CITY=="武汉市"|CITY=="襄阳市"|CITY=="宜昌市"|CITY=="长沙市"|CITY=="南宁市"|CITY=="海口市"|CITY=="重庆市"|CITY=="成都市"|CITY=="贵阳市"|CITY=="遵义市"|CITY=="昆明市"|CITY=="西安市"|CITY=="宝鸡市"|CITY=="兰州市"|CITY=="银川市"|CITY=="西宁市"|CITY=="乌鲁木齐市"|CITY=="昌吉市"|CITY=="石河子市"
replace highinnov=0 if highinnov==.
reghdfe qua1 lian  TobinQ Lev ROA Cashflow ROE if highinnov==1, absorb(Symbol year  IndustryCode) vce(r) //显著
est store ffe_1
reghdfe qua1 lian  TobinQ Lev ROA Cashflow ROE if highinnov==0, absorb(Symbol year  IndustryCode) vce(r)  //不显著
est store ffe_2
*---行业异质性
gen highind=1 if IndustryCode=="C25"|IndustryCode=="C26"|IndustryCode=="C27"|IndustryCode=="C28"|IndustryCode=="C29"|IndustryCode=="C31"|IndustryCode=="C32"|IndustryCode=="C34"|IndustryCode=="C35"|IndustryCode=="C36"|IndustryCode=="C37"|IndustryCode=="C38"|IndustryCode=="C39"|IndustryCode=="C40"|IndustryCode=="C41"|IndustryCode=="I63"|IndustryCode=="I64"|IndustryCode=="I65"|IndustryCode=="M73"
replace highind=0 if highind==.

reghdfe qua1 lian  TobinQ Lev ROA Cashflow ROE if highind==1, absorb(Symbol year  IndustryCode) vce(r) //显著
est store ffe_3
reghdfe qua1 lian  TobinQ Lev ROA Cashflow ROE if highind==0, absorb(Symbol year  IndustryCode) vce(r)  //不显著
est store ffe_4
*----企业自身性质
merge m:1 Symbol using "qiyexingzhi"
keep if _merge==3
drop _merge
tab CompanyProperty
reghdfe qua1 lian  TobinQ Lev ROA Cashflow ROE if CompanyProperty=="P5511", absorb(Symbol year  IndustryCode) vce(r)
est store f5_1
 // 国有 显著
reghdfe qua1 lian  TobinQ Lev ROA Cashflow ROE if CompanyProperty!="P5511", absorb(Symbol year  IndustryCode) vce(r)
est store f5_2
 //非国有 不显著
 
reghdfe qua1 lian  TobinQ Lev ROA Cashflow ROE if CompanyProperty=="P5517", absorb(Symbol year  IndustryCode) vce(r)

est store ffe_7
 //私营 不显著
reghdfe qua1 lian  TobinQ Lev ROA Cashflow ROE if CompanyProperty=="P553", absorb(Symbol year  IndustryCode) vce(r)
est store ffe_8
 //外商投资 显著
reghdfe qua1 lian  TobinQ Lev ROA Cashflow ROE if CompanyProperty=="P5531", absorb(Symbol year  IndustryCode) vce(r)  //中外合资 不显著
reghdfe qua1 lian  TobinQ Lev ROA Cashflow ROE if CompanyProperty=="P555", absorb(Symbol year  IndustryCode) vce(r) //行政机关事业单位 显著为负
reghdfe qua1 lian  TobinQ Lev ROA Cashflow ROE if CompanyProperty=="P559", absorb(Symbol year  IndustryCode) vce(r) //其他 不显著 

*---------
esttab f5_*  using final5.rtf, replace                  ///
						mtitle(`m') compress nogap b(%6.3f)       ///
						scalars(r2_a N F) star(* 0.1 ** 0.05 *** 0.01)	
						
						
				